
#include <fstream>
#include "FileSystem.h"

namespace LuaGui {

    // path
    //std::string FileSystem::FormatPath(std::string path)
    //{
    //    fs::path _path = LuaGui::Utf8ToUnicode(path);
    //    return fs::path(path).lexically_normal().u16string();
    //}
    bool FileSystem::Exists(fs::path& path, fs::file_status status)
    {
        return fs::status_known(status) ? fs::exists(status) : fs::exists(path);
    }

    fs::path FileSystem::GetCurrentPath()
    {
        return fs::current_path();
    }

    bool FileSystem::IsDirectory(fs::path& path)
    {
        return fs::is_directory(path);
    }

    bool FileSystem::IsRegularFile(fs::path& path)
    {
        return fs::is_regular_file(path);
    }

    static void s_add_file_to_vector(std::vector<std::string>& vec, const fs::directory_entry& e)
    {
        if (e.is_regular_file())
        {
            vec.push_back(e.path().u8string());
        }
    }

    std::vector<std::string> FileSystem::GetFileList(fs::path& path, bool recursive)
    {
        std::vector<std::string> vec;
        if (recursive)
        {
            for (auto& e : fs::recursive_directory_iterator(path))
            {
                s_add_file_to_vector(vec, e);
            }
        }
        else
        {
            for (auto& e : fs::directory_iterator(path))
            {
                s_add_file_to_vector(vec, e);
            }
        }
        return vec;
    }

    bool FileSystem::CreateDirectory(fs::path& path)
    {
        return fs::create_directories(path);
    }

    bool FileSystem::RemoveDirectory(fs::path& path, bool recursive)
    {
        return recursive ? fs::remove_all(path) : fs::remove(path);
    }

    void FileSystem::Rename(fs::path& old_path, fs::path& new_path)
    {
        return fs::rename(old_path, new_path);
    }

    std::string FileSystem::GetFileText(std::string filepath) {
        std::ifstream ifs(filepath, std::ios::binary | std::ios::in);
        if (!ifs) return "";
        std::string text((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
        ifs.close();
        return text;
    }
}
